{% extends 'charts/base.html' %}

{% block options %}
    <ul class="nav ace-nav">
        <li>
            <button class="btn btn-purple btn-sm" id="add_order_btn" type="button">图表订单</button>
        </li>
        <li>
            <div class="dropdown">
                <button class="btn btn-sm btn-pink dropdown-toggle" type="button" id="add_zixuan_menu"
                        data-toggle="dropdown"
                        aria-haspopup="true" aria-expanded="true">
                    <i class="ace-icon fa fa-heart"></i>
                    自选
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu" id="zixuan_zx_names" aria-labelledby="add_zixuan_menu">
                    <li>
                        <div class="checkbox">
                            <label>
                                <input name="form-field-checkbox" type="checkbox" class="ace">
                                <span class="lbl">我的持仓</span>
                            </label>
                        </div>
                    </li>
                </ul>
            </div>
        </li>
        <li>
            <button class="btn btn-sm btn-purple" id="show_datu" type="button" value="0">切换到大图</button>
        </li>
        <li>
            <button class="btn btn-sm btn-purple" id="shuaxin" type="button" value="0">开启自动刷新</button>
        </li>
        <li>
            <form class="form-search" style="width: 235px;">
                <div class="input-group">
                    <input type="text" class="form-control search-query" id="search_code" placeholder="代码搜索"
                           style="height: 42px;"/>
                    <span class="input-group-btn">
                        <button type="button" class="btn btn-purple btn-sm" id="stock_ok" style="margin-top: -13px;">Show</button>
                    </span>
                </div>
            </form>
        </li>
    </ul>
{% endblock %}

{% block sidebar %}

    <div class="tabbable">
        <ul class="nav nav-tabs" id="myTab">
            <li class="active">
                <a data-toggle="tab" href="#tab-stocks" aria-expanded="true">
                    代码列表
                </a>
            </li>

            <li class="">
                <a data-toggle="tab" href="#tab-jhs" aria-expanded="false">
                    机会列表
                </a>
            </li>

        </ul>

        <div class="tab-content">
            <div id="tab-stocks" class="tab-pane fade active in">
                <div class="btn-group btn-corner">
                    {% for zx in zx_list %}
                        <button class="btn btn-sm btn-info btn_zixuan"
                                data-zxname="{{ zx.name }}">{{ zx.short_name }}</button>
                    {% endfor %}
                </div>

                <div class="from-group">
                    <input class="form-control" id="stock_search" placeholder="Search" type="text"/>
                </div>

                <div class="stocks_list">
                    <div>
                        <ul class="nav nav-list" id="my_stocks">

                        </ul><!-- /.nav-list -->
                    </div>
                </div>
            </div>

            <div id="tab-jhs" class="tab-pane fade">
                <div class="stocks_list">
                    <ul class="list-group" id="jhs_ul">
                        <li class="list-group-item">Loading</li>
                    </ul>
                </div>

            </div>
        </div>
    </div>
{% endblock %}

{% block content %}
    {# 选项设置 #}
    <div class="ace-settings-container" id="ace-settings-container">
        <div class="btn btn-app btn-xs btn-warning ace-settings-btn" id="ace-settings-btn">
            <i class="ace-icon fa fa-tachometer bigger-130"></i>
        </div>

        <div class="ace-settings-box clearfix chart_setting" id="ace-settings-box">

        </div><!-- /.ace-settings-box -->
    </div><!-- /.ace-settings-container -->

    <div class="row" style="margin-left: -4px;">
        <div id="kline_high" class="kline_chart"
             style="float:left;width: calc(100% - 56px);height:100px;min-height: 320px;"></div>
        <div class="btn-toolbar" role="toolbar" aria-label="周期选择"
             style="float:right;margin-top: 40px; width: 55px;height:320px;max-width: 55px;min-width: 55px;">
            <div class="btn-group btn-group-vertical btn-group-xs btn-corner" role="group" id="zq_high">
                {% for zq, name in support_frequencys.items %}
                    <button type="button" class="btn btn-xs btn-default" data-zq="{{ zq }}">{{ name }}</button>
                {% endfor %}
            </div>
        </div>
    </div>
    <hr style="margin-top: 2px; margin-bottom: 2px;"/>
    <div class="row" style="margin-left: -4px;">
        <div id="kline_low" class="kline_chart"
             style="float:left;width: calc(100% - 56px);height:100px;min-height: 320px;"></div>
        <div class="btn-toolbar" role="toolbar" aria-label="周期选择"
             style="float:right; width: 55px;height:320px;max-width: 55px;min-width: 55px;">
            <div class="btn-group btn-group-vertical btn-group-xs btn-corner" role="group" id="zq_low">
                {% for zq, name in support_frequencys.items %}
                    <button type="button" class="btn btn-xs btn-default" data-zq="{{ zq }}">{{ name }}</button>
                {% endfor %}
            </div>
        </div>
    </div>
    <div class="tabbable">
        <ul class="nav nav-tabs tab-color-blue" id="my_account">
            <li class="active">
                <a data-toggle="tab" href="#balance_positions" aria-expanded="false">资金&持仓</a>
            </li>

            <li class="">
                <a data-toggle="tab" href="#opt_records" aria-expanded="false">操作记录</a>
            </li>
        </ul>

        <div class="tab-content">
            <div id="balance_positions" class="tab-pane fade in active">
                <div class="well">
                    <div style="width: 70%; float:left;">
                        总资产：<span id="balance_total">0.00</span> USDT
                        可用: <span id="balance_free">0.00</span> USDT
                        已用: <span id="balance_used">0.00</span> USDT
                        未实现盈亏：<span id="balance_profit">0.00</span> USDT
                    </div>
                    <div style="width: 15%; float:right;">
                        <button class="btn btn-minier btn-success" style="float: right;" id="balance_shuaxin">刷新
                        </button>
                    </div>
                    <div style="clear: both;"></div>
                </div>

                <table class="table table-bordered table-hover">
                    <thead>
                    <tr>
                        <td>币种</td>
                        <td>方向</td>
                        <td>杠杆</td>
                        <td>价格</td>
                        <td>数量</td>
                        <td>盈亏</td>
                        <td>操作</td>
                    </tr>
                    </thead>
                    <tbody id="currency_positions">

                    </tbody>
                </table>
            </div>

            <div id="opt_records" class="tab-pane">
                <table class="table table-striped table-bordered table-hover table_data" style="width: 100%;">
                    <thead>
                    <tr>
                        <td>时间</td>
                        <td>标的</td>
                        <td>信息</td>
                    </tr>
                    </thead>
                    <tbody id="currency_opt_records">

                    </tbody>
                </table>
            </div>
        </div>
    </div>

    {% include 'charts/order_opt.html' with market='currency' %}
{% endblock %}


{% block js %}
    <script type="text/javascript">
        $(
            function () {
                var chart_div_high = getClientHeight() - 58;

                $('.stocks_list').ace_scroll({
                    size: 600
                });

                var market = 'currency';
                var code = '{{default_code}}';
                var name = '{{default_code}}';
                var frequency_high = '4h';
                var frequency_low = '30m';
                var cookie_pre = '_currency'
                var intervalId = undefined; // 定时任务执行ID
                var url = window.location.href;
                if (url.split('#').length === 2) {
                    code = url.split('#')[1]
                }
                // 图表对象
                var chart_high = echarts.init(document.getElementById('kline_high'), 'dark', {renderer: 'canvas'});
                var chart_low = echarts.init(document.getElementById('kline_low'), 'dark', {renderer: 'canvas'});

                // 全局js
                {% include 'charts/fun.js' %}
                {% include 'charts/global.js' %}

                // 缠论配置项
                {% include 'charts/options.js' %}

                // 新增订单
                {% include 'charts/order_opt.js' %}

                // 自动触发一次
                $('.btn_zixuan')[0].click();
                query_cl_chart_config(market, code);
                fetchKlinesData(chart_high, market, code, frequency_high, true);
                fetchKlinesData(chart_low, market, code, frequency_low, true);
                zixuan_code_query_zx_names(market, code);
                // 机会列表
                jhs_list_show();
                setInterval(jhs_list_show, 60000);


                // 操作账户资金
                function show_currency_balances() {
                    $.ajax({
                        type: "GET",
                        url: "/currency/balances",
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] === 200) {
                                $('#balance_total').html(parseFloat(result['data']['total']).toFixed(4));
                                $('#balance_free').html(parseFloat(result['data']['free']).toFixed(4));
                                $('#balance_used').html(parseFloat(result['data']['used']).toFixed(4));
                                $('#balance_profit').html(parseFloat(result['data']['profit']).toFixed(4));
                            } else {
                                alert('获取账户资金失败');
                            }
                        }
                    });
                }

                show_currency_balances();

                // 查询账户持仓
                function show_currency_positions() {
                    $.ajax({
                        type: "GET",
                        url: "/currency/positions",
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] === 200) {
                                $('#currency_positions').html('');
                                for (var i = 0; i < result['data'].length; i++) {
                                    var p = result['data'][i];
                                    $('#currency_positions').append(
                                        '<tr>' +
                                        '<td><a href="#' + p.symbol + '" class="code" data-code="' + p.symbol + '" data-name="' + p.symbol + '">' + p.symbol + '</a></td>' +
                                        '<td>' + p.side + '</td>' +
                                        '<td>' + p.leverage + '</td>' +
                                        '<td>' + p.entryPrice + '</td>' +
                                        '<td>' + parseFloat(p.contracts).toFixed(4) + ' (' + parseFloat(p.initialMargin).toFixed(4) + ')</td>' +
                                        '<td>' + parseFloat(p.unrealizedPnl).toFixed(4) + ' USDT ' + parseFloat(p.percentage).toFixed(2) + '%</td>' +
                                        '<td><button type="button" class="pos_close_btn" data-code="' + p.symbol + '">市价平仓</button></td>' +
                                        '</tr>'
                                    );
                                }
                            } else {
                                alert('获取账户持仓失败');
                            }
                        }
                    });
                }

                show_currency_positions();

                // 平仓操作
                $("body").delegate('.pos_close_btn', 'click', function () {
                    let code = $(this).attr('data-code');
                    if (confirm('确定要将 ' + code + ' 按市价进行平仓？')) {
                        $.ajax({
                            type: "GET",
                            url: "/currency/pos_close?code=" + code,
                            dataType: 'json',
                            success: function (result) {
                                if (result['code'] === 200) {
                                    show_currency_positions();
                                    $.message({message: '已平仓', type: 'success'});
                                } else {
                                    $.message({message: result['msg'], type: 'error'});
                                }
                            }
                        });
                    }
                });

                // 操作记录查询
                function show_currency_opt_records() {
                    $.ajax({
                        type: "GET",
                        url: "/currency/opt_records",
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] === 200) {
                                $('#currency_opt_records').html('');
                                for (var i = 0; i < result['data'].length; i++) {
                                    res = result['data'][i];
                                    $('#currency_opt_records').append('<tr><td>' + res['datetime'] + '</td><td><a href="#' + res['symbol'] + '" class="code" data-code="' + res['symbol'] + '" data-name="' + res['symbol'] + '">' + res['symbol'] + '</a></td><td>' + res['info'] + '</td></tr>');
                                }
                                $('.table_data').DataTable({});
                            } else {
                                alert('获取操作记录失败');
                            }
                        }
                    });
                }

                show_currency_opt_records();

                // 账户资产与持仓刷新
                $('#balance_shuaxin').click(function () {
                    show_currency_balances();
                    show_currency_positions();
                });

                // 机会列表的展示
                function jhs_list_show() {
                    $.ajax({
                        type: "GET",
                        url: "/currency/jhs",
                        dataType: 'json',
                        success: function (result) {
                            if (result['code'] === 200) {
                                $('#jhs_ul').html('');
                                for (let i = 0; i < result['data'].length; i++) {
                                    jh = result['data'][i];
                                    $('#jhs_ul').append('<li class="list-group-item"><p class="list-group-item-heading"><a href="javascript:void(0);" class="code" data-code="' + jh['code'] + '" data-name="' + jh['code'] + '">' + jh['name'] + '</a> <span>' + jh['frequency'] + '</span></p> <p class="list-group-item-text">' + jh['jh_type'] + ' <br/>' + jh['is_done'] + ' ' + jh['is_td'] + '<br/> ' + jh['datetime_str'] + '</p></li>');
                                }
                            }
                        }
                    });
                }

            }
        );
    </script>
{% endblock %}